package com.yzt.index;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.yzt.zhuju.arouter.RouterMain;
import com.yzt.zhuju.config.AppConfig;
import com.yzt.zhuju.event.RxBus;
import com.yzt.zhuju.event.call.AgoraCallEvent;
import com.yzt.zhuju.network.entity.call.AgoraCallMsg;
import com.yzt.zhuju.utils.ActivityManagerUtils;
import com.yzt.p_base.utils.AppInfoUtils;
import com.yzt.p_base.utils.DateUtils;
import com.yzt.p_base.utils.LogDataUtils;

import rx.Subscription;

/**
 * 在内存和电量不足的时候不会被自动杀死的前台Service
 * 需要在AndroidMainfest中注册
 * 也需要<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />权限
 */
public class KeepAliveService extends Service {

    public static void startKeepAliveService(Context context) {
        //启动服务
        if (!KeepAliveService.serviceIsLive) {
            // Android 8.0使用startForegroundService在前台启动新服务
            Intent intent = new Intent(context, KeepAliveService.class);
            intent.putExtra("Foreground", "This is a foreground service.");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent);
            } else {
                context.startService(intent);
            }
        }
    }

    public static void stopKeepAliveService(Context context) {
        //停止服务
        Intent intent = new Intent(context, KeepAliveService.class);
        context.stopService(intent);
    }

    Handler mHandler;

    private static final String TAG = KeepAliveService.class.getSimpleName();

    public static boolean serviceIsLive = false;

    private final int NOTIFICATION_ID = 1001;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "onCreate");
        // 获取服务通知
        Notification notification = createForegroundNotification();
        //将服务置于启动状态 ,NOTIFICATION_ID指的是创建的通知的ID
        startForeground(NOTIFICATION_ID, notification);

        // 注册订阅
        rxEvent = RxBus.getDefault().observerRxBusSticky(AgoraCallEvent.class, event -> {
            Activity mainActivity = ActivityManagerUtils.getInstance().findActivity(MainActivity.class);
            //如果MainActivity被销毁了，则处理通话事件；如果MainActivity存在，则由MainActivity处理
            if (mainActivity == null || mainActivity.isDestroyed()) {
                callAccept(event.getMsg());
            }
        });
    }

    private Subscription rxEvent;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.e(TAG, "onBind");
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand");
        mHandler = new Handler();
        // 标记服务启动
        KeepAliveService.serviceIsLive = true;
        // 数据获取
//        String data = intent.getStringExtra("Foreground");
//        Toast.makeText(this, data, Toast.LENGTH_SHORT).show();
//        try {
//            activityClass = Class.forName(intent.getStringExtra("Class"));
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        }

        // 获取服务通知
//        Notification notification = createForegroundNotification();
//        //将服务置于启动状态 ,NOTIFICATION_ID指的是创建的通知的ID
//        startForeground(NOTIFICATION_ID, notification);

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy");

        // 移除所有订阅服务
        RxBus.getDefault().removeStickyEvent(rxEvent.getClass());
        rxEvent.unsubscribe();
        // 标记服务关闭
        KeepAliveService.serviceIsLive = false;
        // 移除服务
        stopForeground(true);

        super.onDestroy();
    }

    /**
     * 创建服务通知
     */
    private Notification createForegroundNotification() {
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // 唯一的通知通道的id.
        String notificationChannelId = "other_channel";

        // Android8.0以上的系统，新建消息通道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //用户可见的通道名称
            String channelName = "其它通知消息";
            //通道的重要程度
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel notificationChannel = new NotificationChannel(notificationChannelId, channelName, importance);
            notificationChannel.setDescription("Channel description");
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(notificationChannel);
            }
        }

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, notificationChannelId);
        //通知小图标
        builder.setSmallIcon(R.mipmap.logo);
        //通知标题
        builder.setContentTitle(AppInfoUtils.getAppName(AppConfig.context));
        //通知内容
        builder.setContentText(getString(R.string.nomi_in_bg_receive_video_call));
        //设定通知显示的时间
        builder.setWhen(System.currentTimeMillis());
        //设定启动的内容
        Activity activity = ActivityManagerUtils.getInstance().getActivity();
        Intent activityIntent = new Intent(this, (activity != null && TextUtils.equals(activity.getClass().getSimpleName(), "ChatRoomActivity")) ? activity.getClass() : MainActivity.class);
        PendingIntent pendingIntent;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
            pendingIntent = PendingIntent.getActivity(this, 1, activityIntent, PendingIntent.FLAG_IMMUTABLE);
        } else {
            pendingIntent = PendingIntent.getActivity(this, 1, activityIntent, PendingIntent.FLAG_ONE_SHOT);
        }
        builder.setContentIntent(pendingIntent);

        //创建通知并返回
        return builder.build();
    }

    //声网音视屏推送处理
    private boolean isGoOut;
    private long timeDate;
    private AgoraCallMsg mCallMsg;

    public void callAccept(AgoraCallMsg msg) {
        LogDataUtils.d("agora_data", "" + msg);
        isGoOut = false;
        switch (msg.getStatus()) {
            case 1:
                //进入/唤起接收页面
                this.mCallMsg = msg;
                this.timeDate = DateUtils.getNowTimeStamp();
                mHandler.postDelayed(runnable, 1000);
                break;
            case 2:
                //离开/拒绝 挂断
                if (mCallMsg != null && TextUtils.equals(mCallMsg.getInitiateUid(), msg.getCloseUid())) {
                    long nowTime = DateUtils.getNowTimeStamp();
                    if (nowTime - timeDate < 1000) {
                        isGoOut = true;
                        mHandler.removeCallbacks(runnable);
                    } else {
                 //       ARouter.getInstance().navigation(ICallService.class).hangUp();
                    }
                } else {
                  //  ARouter.getInstance().navigation(ICallService.class).hangUp();
                }
                break;
            default:
                break;
        }
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (isGoOut) {
                return;
            }
            RouterMain.MainActivity(mCallMsg);
        }
    };
}
